package top.huxy.boot.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.huxy.boot.model.entity.ExceptionLog;
import top.huxy.boot.service.ExceptionLogService;
import top.huxy.boot.util.obj.ThreadLocalRequestDetail;

/**
 * @author HuXY
 * @Classname ExceptionUtils
 * @Description ExceptionUtils
 * @Date 2021/9/19 14:55
 * @Created by huxy
 */
@Component
@Slf4j
public class ExceptionUtils {

    private static ExceptionLogService exceptionLogService;

    @Autowired
    public void setExceptionLogService(ExceptionLogService exceptionLogService) {
        ExceptionUtils.exceptionLogService = exceptionLogService;
    }

    public static void logError(Throwable th) {
        ThreadLocalRequestDetail current = ThreadLocalRequestDetail.current();
        log.error(th.getMessage(), th);

        if (current != null) {
            current.logError(th);
        } else {
            if (th == null) {
                log.error("th==null，不可写日志");
            } else {
                ExceptionLog exceptionLog = new ExceptionLog(null,
                        StringUtils.getStackTrace(th),
                        th.getMessage(),
                        th.getClass().getName());
                exceptionLogService.saveExceptionLog2Redis(exceptionLog);
            }
        }
    }
}
